﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ZBJF.Warranty.Common.Common;

namespace ZBJF.Warranty.WeiXinPayAPI
{
    public class PayResultNotify
    {
        //是否验证成功
        private bool validateIsSuccess = false;
        //是否验证成功
        public bool ValidateIsSuccess { get { return validateIsSuccess; } }

        /// <summary>
        /// 微信支付结果参数
        /// </summary>
        private WxPayData notifyData = new WxPayData();

        /// <summary>
        /// 需要响应给微信端的数据
        /// </summary>
        private string responseContent = null;

        private HttpRequest request;
        public PayResultNotify(HttpRequest request)
        {
            this.request=request;
            validateIsSuccess = ProcessNotify();
        }

        #region 验证支付结果 +private bool ProcessNotify()
        /// <summary>
        /// 验证支付结果
        /// </summary>
        /// <returns>验证成功：true ;验证失败：false</returns>
        private bool ProcessNotify()
        {
            notifyData = this.GetNotifyData();
            //1、验证签名是否正确
            if (!notifyData.CheckSign())
            {
                //若签名验证错误
                LogHelper.WriteLog(this.GetType().ToString() + ";--签名验证错误：" + notifyData.ToXml(), LogType.error);
                SetResponseContent(ReturnCodeEnum.FAIL, "签名验证错误");
                return false;
            }

            ////2、检查支付结果中transaction_id是否存在
            //if (!notifyData.IsSet("transaction_id"))
            //{
            //    //若transaction_id不存在
            //    LogHelper.WriteLog(this.GetType().ToString() + ";--支付结果中微信订单号不存在：" + notifyData.ToXml(), LogType.error);
            //    responseContent= BuilderResponseContent(ReturnCodeEnum.FAIL, "支付结果中微信订单号不存在");
            //     return false;
            //}

            //string transaction_id = notifyData.GetValue("transaction_id").ToString();

            ////3、查询订单，判断订单真实性
            //if (!PayOrder.OrderIsExists(transaction_id))
            //{
            //    //若订单查询失败
            //    res.SetValue("return_code", "FAIL");
            //    res.SetValue("return_msg", "订单查询失败");
            //    LogHelper.WriteLog(this.GetType().ToString() + ";--订单查询失败：" + notifyData.ToXml(), LogType.error);
            //    responseContent= BuilderResponseContent(ReturnCodeEnum.FAIL, "订单查询失败");
            //     return false;
            //}

            //验证成功
            LogHelper.WriteLog(this.GetType().ToString() + ";--验证支付结果成功：" + notifyData.ToXml(), LogType.remark);
            SetResponseContent(ReturnCodeEnum.SUCCESS, "OK");
            return true;
        }
        #endregion

        #region 获取商城订单号 + string GetOrderNum()
        /// <summary>
        /// 获取商城订单号
        /// </summary>
        /// <returns></returns>
        public string GetOrderNum()
        {
            object obj = notifyData.GetValue("out_trade_no");
            if (obj == null)
                return null;
            else
                return obj.ToString();
        }
        #endregion

        #region 获取响应数据 + string GetResponseContent()
        /// <summary>
        /// 获取响应数据
        /// </summary>
        /// <returns></returns>
        public string GetResponseContent()
        {
            return responseContent;
        }
        #endregion

        #region 设置响应数据 + void SetResponseContent(ReturnCodeEnum return_code,string return_msg)
        public void SetResponseContent(ReturnCodeEnum return_code,string return_msg)
        {
            WxPayData res = new WxPayData();
            res.SetValue("return_code", Enum.GetName(typeof(ReturnCodeEnum), return_code) );
            res.SetValue("return_msg", return_msg);
            responseContent= res.ToXml();
        }
        #endregion

        #region 接收从微信支付后台发送过来的数据并转换成对象 +private WxPayData GetNotifyData()
        /// <summary>
        /// 接收从微信支付后台发送过来的数据
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        private WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            LogHelper.WriteLog(this.GetType().ToString() + ";--微信支付返回数据", LogType.remark);
            WxPayData result = new WxPayData();
            //转换数据格式并验证签名
            try
            {
                result.FromXml(builder.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(this.GetType().ToString() + ";--微信支付返回数据转换异常：" + ex.ToString(), LogType.error);
            }
            return result;
        }
        #endregion

    }
}
